const keyPrefix = 'cloud-'

/**
 * 获取 storage (sessionStorage|localStorage)
 * @param type {string} session | local
 * @return {Storage}
 */
export const getStorage = type => (type === 'session' ? window.sessionStorage : window.localStorage)

/**
 * console.log(startsWith('abc', 'a'))
 * // => true
 *
 * console.log(startsWith('abc', 'b'))
 * // => false
 *
 * console.log(startsWith('abc', 'b', 1))
 * // => true
 *
 * @param str
 * @param target
 * @param position
 * @return {boolean}
 */
export const startsWith = (str, target, position = 0) => {
  return str ? str.slice(position, position + target.length) === target : false
}

/**
 * 存储 Storage
 */
export const setStore = (key, value, options = { type: null }) => {
  const valueKey = keyPrefix + key
  const storage = getStorage(options?.type)
  const item = { value, datetime: Date.now() }
  storage.setItem(valueKey, JSON.stringify(item))
}

/**
 * 获取 Storage
 */

export const getStore = (key, type) => {
  const valueKey = keyPrefix + key
  const storage = getStorage(type)
  const item = storage.getItem(valueKey)
  if (item) {
    try {
      const value = JSON.parse(item)
      return value ? value.content || value.value : null
    } catch (e) {
      return item
    }
  }
  return item
}
/**
 * 删除 Storage
 */
export const removeStore = (key, type) => {
  const valueKey = keyPrefix + key
  const storage = getStorage(type)
  storage.removeItem(valueKey)
}

/**
 * 获取全部 Storage
 */
export const getAllStore = type => {
  const storage = getStorage(type)
  return getAllKeys(type).map(storage.getItem)
}

/**
 * 清空全部 Storage
 */
export const clearStore = type => {
  const storage = getStorage(type)
  getAllKeys(type).forEach(storage.removeItem)
}

/**
 *
 * @param type
 * @return {*[]}
 */
export const getAllKeys = type => {
  const storage = getStorage(type)
  const length = storage.length
  const keys = []
  for (let i = 0; i <= length; i++) {
    const key = storage.key(i)
    if (key && startsWith(key, keyPrefix)) {
      keys.push(key)
    }
  }
  return keys
}
